package com.xht.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xht.constants.SystemConstants;
import com.xht.domain.ResponseResult;
import com.xht.domain.dto.RoleChangeStatusDto;
import com.xht.domain.dto.RoleDto;
import com.xht.domain.entity.Role;
import com.xht.domain.entity.RoleMenu;
import com.xht.enums.AppHttpCodeEnum;
import com.xht.exception.SystemExceptin;
import com.xht.mapper.RoleMapper;
import com.xht.service.RoleMenuService;
import com.xht.service.RoleService;
import com.xht.utils.BeanCopyUtils;
import com.xht.vo.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 角色信息表(SysRole)表服务实现类
 *
 * @author makejava
 * @since 2025-03-04 21:08:01
 */
@Service("RoleService")
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMenuService roleMenuService;

    /**
     * 查Role表,展示集合的 role_name 信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<String> selectRoleKeyByUserId(Long userId) {
        //判断是否是管理员
        if (userId == 1L) {
            List<String> roleKeys = new ArrayList<>();
            roleKeys.add("admin");
            return roleKeys;
        }

        //否则查询用户所具有的角色信息
        return getBaseMapper().selectRoleKeyByUserId(userId);
    }

    /**
     * 查询 role信息 -- 可以模糊查询 ,根据role_sort进行升序排序
     *
     * @param pageNum
     * @param pageSize
     * @param roleName
     * @param status
     * @return
     */
    @Override
    public ResponseResult selectRolePage(Integer pageNum, Integer pageSize, String roleName, String status) {

        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(roleName), Role::getRoleName, roleName);
        queryWrapper.eq(StringUtils.hasText(status), Role::getStatus, status);
        queryWrapper.orderByAsc(Role::getRoleSort);
        Page<Role> page = new Page<>(pageNum, pageSize);
        page(page, queryWrapper);
        List<Role> roleList = page.getRecords();
        //封转数据
        PageVo pageVo = new PageVo(roleList, page.getTotal());

        return ResponseResult.okResult(pageVo);
    }

    /**
     * 修改 指定的role的status字段
     *
     * @param roleDto
     * @return
     */
    @Override
    public ResponseResult changeStatus(RoleChangeStatusDto roleDto) {
        Role role = BeanCopyUtils.copyBean(roleDto, Role.class);
        Long id = roleDto.getRoleId();
        role.setId(id);
        LambdaUpdateWrapper<Role> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Role::getStatus, role.getStatus())
                .eq(Role::getId, id);
        getBaseMapper().update(role, updateWrapper);

        return ResponseResult.okResult();
    }

    /**
     * 添加角色
     *
     * @param roleDto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult addRole(RoleDto roleDto) {
        //将数据添加到 role表
        Role role = BeanCopyUtils.copyBean(roleDto, Role.class);

        String roleName = role.getRoleName();
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Role::getRoleName, roleName);
        Integer count = getBaseMapper().selectCount(queryWrapper);
        if (count > 0 || !StringUtils.hasText(roleName)) {
            throw new SystemExceptin(AppHttpCodeEnum.ROLENAME_EXIST);
        }
        save(role);

        //数据中的menuIds 添加到 role_Menu表中
        Long id = role.getId();//插入数据库后,该role便会加入 对应的自增 id
//        List<RoleMenu> collect = addRoleDto.getMenuIds().stream()
//                .map(new Function<String, RoleMenu>() {
//                    @Override
//                    public RoleMenu apply(String menuId) {
//                        return new RoleMenu(id, Long.parseLong(menuId));
//                    }
//                }).collect(Collectors.toList());
//
//        roleMenuService.saveBatch(collect);
        //先判断是否 有需要加入该数据
        if (roleDto.getMenuIds() != null && !roleDto.getMenuIds().isEmpty()) {
            insertRoleMenu(roleDto, id);
        }
        return ResponseResult.okResult();
    }

    /**
     * 更新role
     *
     * @param roleDto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult updateRole(RoleDto roleDto) {
        Role role = BeanCopyUtils.copyBean(roleDto, Role.class);
        long id = Long.parseLong(roleDto.getId());
        role.setId(id);
        //roleName不能重复
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Role::getRoleName, role.getRoleName())
                .ne(Role::getId, id); //不查询他自己

        Integer count = getBaseMapper().selectCount(queryWrapper);

        if (count > 0) {
            throw new SystemExceptin(AppHttpCodeEnum.ROLENAME_EXIST);
        }
        //否则 更新role表数据
        updateById(role);

        //先删除 所有 该role_id的 数据项
//        LambdaQueryWrapper<RoleMenu> queryWrapper1 = new LambdaQueryWrapper<>();
//        queryWrapper1.eq(RoleMenu::getRoleId, id);
        LambdaQueryWrapper<RoleMenu> wrapper = Wrappers.lambdaQuery(RoleMenu.class)
                .eq(RoleMenu::getRoleId, id);

        roleMenuService.remove(wrapper);
        //再更新
        insertRoleMenu(roleDto, id);
        return ResponseResult.okResult();
    }

    /**
     * 逻辑删除 角色
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteRole(Integer id) {
        LambdaUpdateWrapper<Role> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Role::getId, id)
                .set(Role::getDelFlag, SystemConstants.ROLE_STATUS_DELETE);
        update(updateWrapper);

        return ResponseResult.okResult();
    }

    /**
     * 在 用户管理 展示所有状态正常的角色
     *
     * @return
     */
    @Override
    public ResponseResult listAllRole() {
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Role::getStatus, SystemConstants.ROLE_STATUS_NORMAL);
        List<Role> roleList = list(queryWrapper);

        return ResponseResult.okResult(roleList);
    }


    //数据中的menuIds 添加到 role_Menu表中
    private void insertRoleMenu(RoleDto roleDto, Long id) {
        List<RoleMenu> collect = roleDto.getMenuIds().stream()
                .map(new Function<String, RoleMenu>() {

                    @Override
                    public RoleMenu apply(String s) {
                        return new RoleMenu(id, Long.parseLong(s));
                    }
                }).collect(Collectors.toList());
        roleMenuService.saveBatch(collect);
    }
}

